package com.sky.wsp.sql.scanner.utils;

import cn.hutool.core.lang.JarClassLoader;
import org.jd.core.v1.api.loader.Loader;
import org.jd.core.v1.api.loader.LoaderException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 在此输入描述
 * @date 2024/11/12
 */
public class JdLoader implements Loader {
    private JarClassLoader jarClassLoader;

    @Override
    public byte[] load(String internalName) throws LoaderException {
        String clazz = addClaszzExt(internalName);
        InputStream is = jarClassLoader.getResourceAsStream(clazz);

        if (is == null) {
            return null;
        } else {
            try (InputStream in = is; ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int read = in.read(buffer);

                while (read > 0) {
                    out.write(buffer, 0, read);
                    read = in.read(buffer);
                }

                return out.toByteArray();
            } catch (IOException e) {
                throw new LoaderException(e);
            }
        }
    }

    @Override
    public boolean canLoad(String internalName) {
        String clazz = packagePathName(internalName);
        try {
            jarClassLoader.loadClass(clazz);
            return true;
        } catch (ClassNotFoundException | NoClassDefFoundError e) {
//            System.err.println(internalName + " 类加载失败: " + e.getMessage());
            return false;
        }
    }

    private String packagePathName(String internalName) {
        String clazz = internalName.replace('/', '.').replace('\\', '.');
        if (clazz.endsWith(".class")) {
            clazz = clazz.substring(0, clazz.lastIndexOf('.'));
        }
        return clazz;
    }

    private String addClaszzExt(String internalName) {
        if (internalName.endsWith(".class")) {
            return internalName;
        }
        return internalName + ".class";
    }

    public void setJarClassLoader(JarClassLoader jarClassLoader) {
        this.jarClassLoader = jarClassLoader;
    }
}
